package com.hao.tool.web.util;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;

/**
 * 保存文件工具类
 * Created by RuiHaoZ on 2018/3/26 21:01
 */
public class FileSaveUtil {


    /**
     * @param filePath 文件路径
     * @param fileName 文件名
     * @return 下载文件
     * @throws IOException
     */
    public static ResponseEntity<byte[]> download(String filePath, String fileName) throws IOException {
//        logger.info("开始下载模板文件");
        File file = new File(filePath);
        HttpHeaders headers = new HttpHeaders();
        fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        //为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        logger.info("模板文件下载成功");
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
}
